package jianzhiOffer;

import java.util.Deque;
import java.util.LinkedList;

public class Codec {
        public String serialize(TreeNode root) {
            if(root == null) return "[]";
            StringBuilder sb = new StringBuilder();
            Deque<TreeNode> queue = new LinkedList<>();
            sb.append("[");
            queue.offer(root);
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if(node != null) {
                    queue.offer(node.left);
                    queue.offer(node.right);
                    sb.append(node.val);
                    sb.append(",");
                }else {
                    sb.append("null");
                    sb.append(",");
                }
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("]");
            return sb.toString();
        }
        public TreeNode deserialize(String data) {
            if(data.equals("[]")) return null;
            String[] res = data.substring(1,data.length() - 1).split(",");
            TreeNode root = new TreeNode(Integer.parseInt(res[0]));
            Deque<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int i = 1;
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll();
                if(!res[i].equals("null")) {
                    node.left = new TreeNode(Integer.parseInt(res[i]));
                    queue.offer(node.left);
                }
                i++;
                if(!res[i].equals("null")) {
                    node.right = new TreeNode(Integer.parseInt(res[i]));
                    queue.offer(node.right);
                }
                i++;
            }
            return root;
        }
}

